// [LICENCE-HEADER]
//

package org.libermundi.theorcs.core.tapestry.services.impl;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;

import org.apache.tapestry5.ioc.Resource;
import org.libermundi.theorcs.core.CoreConstants;
import org.libermundi.theorcs.core.tapestry.services.FreeMarkerService;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * The Class FreeMarkerServiceImpl.
 */
public class FreeMarkerServiceImpl implements FreeMarkerService {
	private static final long serialVersionUID = -4590812394070866146L;

	/** The Constant APPLIED_CHARSET. */
    private static final Charset APPLIED_CHARSET = Charset.forName(CoreConstants.CHARACTER_ENCODING);

    /** The _configuration. */
    private Configuration _configuration;
    
    /**
     * Instantiates a new free marker service impl.
     *
     * @param configuration the configuration
     */
    public FreeMarkerServiceImpl(Configuration configuration) {
        _configuration = configuration;
    }

    /*
     * (non-Javadoc)
     * @see org.libermundi.theorcs.core.tapestry.services.FreeMarkerService#mergeDataWithResource(org.apache.tapestry5.ioc.Resource, java.io.OutputStream, java.lang.Object)
     */
    @Override
    public void mergeDataWithResource(Resource template, OutputStream outputStream, Object rootMap) {
        try {
            String path = template.getPath();
            Template freeMarkerTemplate = _configuration.getTemplate(path, "utf-8");
            Writer out = new OutputStreamWriter(outputStream, APPLIED_CHARSET);
            freeMarkerTemplate.process(rootMap, out);
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /*
     * (non-Javadoc)
     * @see org.libermundi.theorcs.core.tapestry.services.FreeMarkerService#mergeDataWithStream(java.io.InputStream, java.io.OutputStream, java.lang.Object)
     */
    @Override
    public void mergeDataWithStream(InputStream templateStream, OutputStream outputStream, Object rootMap) {
        try {
            Template freeMarkerTemplate = new Template("doedel", new InputStreamReader(templateStream), _configuration);
            Writer out = new OutputStreamWriter(outputStream, APPLIED_CHARSET);
            freeMarkerTemplate.process(rootMap, out);
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
